<template>
  <div class="user-profile">
    <!-- 头部tabbar -->
    <van-nav-bar class="login-nav-bar" title="用户资料" left-arrow @click-left="$router.back()" />

    <!-- 信息单元格 -->
    <input type="file" hidden ref="inputFile" @change="inputChange" />
    <van-cell title="头像" is-link @click="$refs.inputFile.click()">
      <van-image class="avatar" fit="cover" round :src="user.photo" />
    </van-cell>
    <van-cell title="昵称" @click="isShowUpdateName = true" :value="user.name" is-link />
    <van-cell title="性别" :value="user.gender ? '女' : '男'" is-link />
    <van-cell title="生日" :value="user.birthday || '未知'" is-link />

    <!-- 编辑昵称弹层 -->
    <van-popup v-model="isShowUpdateName" style="height: 100%" position="bottom">
      <update-name v-if="isShowUpdateName" @close="isShowUpdateName = false" v-model="user.name" />
    </van-popup>

    <!-- 编辑头像弹层 -->
    <van-popup v-model="isShowUpdateAvatar" style="height: 100%" position="bottom"> <update-avatar v-if="isShowUpdateAvatar" :img="img" @close="isShowUpdateAvatar = false" @update-avatar="user.photo = $event"/>
    </van-popup>
  </div>
</template>

<script>
import { getUserProfile } from '@/api/user.js'
import UpdateName from './components/update-name.vue'
import UpdateAvatar from './components/update-avatar.vue'

export default {
  name: 'UserProfile',
  components: {
    UpdateName,
    UpdateAvatar
  },
  data() {
    return {
      user: {},
      isShowUpdateName: false,
      isShowUpdateAvatar:false,
      img:null
    }
  },
  methods: {
    async loadProfile() {
      try {
        const { data: res } = await getUserProfile()
        // console.log(res);
        this.user = res.data
      } catch (err) {
        this.$toast('获取数据失败')
      }
    },
    inputChange() {
      const file = this.$refs.inputFile.files[0]
      // 获取blob数据
      this.img= window.URL.createObjectURL(file)
    //   console.log(this.img)
      this.isShowUpdateAvatar = true
    },
  },
  created() {
    this.loadProfile()
  },
}
</script>

<style lang="less" scoped>
.user-profile {
  .avatar {
    width: 60px;
    height: 60px;
  }
  .van-popup {
    background: #f5f7f9;
  }
}
</style>